<template>
  <div class="reminder-container">
    <!-- 修改顶部查询区域 -->
    <div class="query-bar">
      <el-select
          v-model="query.relationType"
          placeholder="关系类型"
          clearable
          style="width: 120px"
      >
        <el-option label="配偶" value="配偶" />
        <el-option label="子女" value="子女" />
        <el-option label="其他" value="其他" />
      </el-select>

      <el-input
          v-model="query.realName"
          placeholder="老人姓名"
          clearable
          style="width: 160px; margin-left: 8px"
      />

      <el-button type="primary" @click="handleSearch" style="margin-left: 8px">
        查询
      </el-button>

      <el-button @click="resetQuery">重置</el-button>
    </div>

    <!-- 卡片区域 -->
    <div class="card-grid">
      <!-- 新建提醒卡片 -->
      <div class="card add-card" @click="openAddDialog">
        <div class="plus-icon">+</div>
        <div class="label">新建用药提醒</div>
      </div>

      <!-- 提醒卡片 -->
      <!-- 提醒卡片 -->
      <div
          v-for="r in filteredReminderList"
          :key="r.reminderId"
          class="card reminder-card"
          :class="{ expired: isExpired(r) }"
          @click="openEditDialog(r)"
      >
        <div class="title">提醒老人：{{ r.elderlyName }}</div>
        <div class="title">药品名称：{{ r.medicationName }}</div>
        <div class="dosage">剂量：{{ r.dosage }}</div>
        <div class="countdown">倒计时：{{ getCountdown(r) }}</div>
        <div class="next-time">
          下次提醒时间：{{ formatNextTime(r) }}
        </div>
        <el-tag :type="r.isActive ? 'success' : 'info'">
          {{ r.isActive ? '启用' : '禁用' }}
        </el-tag>
      </div>
    </div>

    <!-- 新建 / 编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑用药提醒' : '新建用药提醒'"
        width="500px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="选择老人" v-if="!isEdit" required>
          <el-select v-model="form.elderlyUserId" placeholder="请选择老人">
            <el-option
                v-for="e in elderlyList"
                :key="e.elderlyUserId"
                :label="e.realName"
                :value="e.elderlyUserId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="药品名称" required>
          <el-input v-model="form.medicationName" />
        </el-form-item>
        <el-form-item label="剂量" required>
          <el-input v-model="form.dosage" />
        </el-form-item>
        <el-form-item label="服用频率" required>
          <el-select v-model="form.frequency" placeholder="请选择频率">
            <el-option label="每天" value="每天" />
            <el-option label="每周" value="每周" />
            <el-option label="每月" value="每月" />
          </el-select>
        </el-form-item>
        <el-form-item label="提醒时间" required>
          <el-time-picker
              v-model="form.reminderTime"
              format="HH:mm:ss"
              value-format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="提醒日" required>
          <el-checkbox-group v-model="form.reminderDays">
            <el-checkbox
                v-for="d in weekDays"
                :key="d.value"
                :label="d.value"
            >
              {{ d.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="开始日期" required>
          <el-date-picker
              v-model="form.startDate"
              type="date"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
              v-model="form.endDate"
              type="date"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="danger"
            @click="deleteReminder(form.reminderId)"
            v-if="isEdit"
        >
          删除
        </el-button>
        <el-button type="warning" @click="toggleStatus(form)" v-if="isEdit">
          {{ form.isActive ? '禁用' : '启用' }}
        </el-button>
        <el-button type="primary" @click="submitForm">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, inject, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import mitt from 'mitt'
import isBetween from 'dayjs/plugin/isBetween'
import weekday from 'dayjs/plugin/weekday'

dayjs.extend(isBetween)
dayjs.extend(weekday)

const emitter = mitt()
const BASE_URL = 'http://localhost:8080'
const token = localStorage.getItem('token')
const currentUser = inject('currentUser')
/* 响应式数据 */
const elderlyList = ref([])
const selectedElderlyId = ref(null)
const reminderList = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const query = ref({
  relationType: '',
  realName: ''
})
const defaultAvatar = new URL('@/assets/images/default-avatar.png', import.meta.url).href
const boundElderlyList = ref([])
// 获取头像URL（添加时间戳避免缓存）
const getAvatarUrl = (url) => {
  if (!url) return defaultAvatar;
  return `${url}?t=${Date.now()}`; // 添加时间戳确保实时加载
};

// 头像加载失败处理
const handleAvatarError = (elderly) => {
  elderly.avatarUrl = defaultAvatar; // 加载失败时回退到默认头像
};
const weekDays = [
  { label: '周一', value: '1' },
  { label: '周二', value: '2' },
  { label: '周三', value: '3' },
  { label: '周四', value: '4' },
  { label: '周五', value: '5' },
  { label: '周六', value: '6' },
  { label: '周日', value: '7' }
]

const form = ref({
  reminderId: null,
  elderlyUserId: null,
  familyUserId: 1,
  medicationName: '',
  dosage: '',
  frequency: '每天',
  reminderTime: '08:00:00',
  reminderDays: [],
  startDate: '',
  endDate: '',
  remark: '',
  isActive: 1
})

let timer = null

/* 全局提醒监听 */
emitter.on('showReminder', async ({ r }) => {
  try {
    await ElMessageBox.confirm(
        `用药时间到！请服用：${r.medicationName}（${r.dosage}）`,
        '用药提醒',
        {
          confirmButtonText: '已服用',
          cancelButtonText: '5分钟后再提醒',
          distinguishCancelAndClose: true,
          type: 'warning'
        }
    )
  } catch (action) {
    if (action === 'cancel') {
      setTimeout(() => emitter.emit('showReminder', { r }), 5 * 60 * 1000)
    }
  }
})

const filteredReminderList = computed(() => {
  let list = reminderList.value

  // 根据老人姓名过滤
  const kw = (query.value.realName ?? '').toLowerCase()
  if (kw.trim()) {
    list = list.filter(r =>
        (r.elderlyName ?? '').toLowerCase().includes(kw)
    )
  }

  // 根据关系类型过滤
  const rt = query.value.relationType
  if (rt) {
    list = list.filter(r => {
      const elderly = elderlyList.value.find(e => e.elderlyUserId === r.elderlyUserId)
      return elderly && elderly.relationType === rt
    })
  }

  return list
})

// 修改查询方法
const handleSearch = async () => {
  const token = localStorage.getItem('token')
  const { data } = await axios.get(
      `${BASE_URL}/api/v1/family_user/elderly/boundElderly/search`,
      {
        params: {
          familyUserId: currentUser.value.userId,
          relationType: query.value.relationType,
          realName: query.value.realName
        },
        headers: { Authorization: `Bearer ${token}` }
      }
  )
  if (data.code === 2000) {
    elderlyList.value = data.data
  }
}

// 修改重置方法
const resetQuery = () => {
  query.value = { relationType: '', realName: '' }
  handleSearch()
}
/* 加载提醒 */
const loadReminders = async () => {
  const token = localStorage.getItem('token')
  const familyUserId = currentUser.value?.userId

  if (!familyUserId) {
    ElMessage.error("未登录或用户信息缺失")
    return
  }

  try {
    const { data } = await axios.get(
        `${BASE_URL}/api/v1/family_user/medication_reminder/listByFamily`,
        {
          params: { familyUserId },
          headers: { Authorization: `Bearer ${token}` }
        }
    )
    if (data.code === 2000) {
      reminderList.value = data.data || []
    }
  } catch (error) {
    console.error("加载提醒失败:", error.response?.data || error.message)
    ElMessage.error("加载用药提醒失败")
  }
}
/* 时间计算 */
const getNextReminderTime = (r) => {
  const [h, m, s] = r.reminderTime.split(':')
  const days = r.reminderDays.split(',').map(Number)
  let next = dayjs().hour(h).minute(m).second(s)
  for (let i = 0; i < 7; i++) {
    const candidate = next.add(i, 'day')
    if (days.includes(candidate.day()) && candidate.isAfter(dayjs())) {
      return candidate
    }
  }
  return null
}

const getCountdown = (r) => {
  const now = dayjs()
  const next = getNextReminderTime(r)
  if (!next) return '已结束'
  const diff = next.diff(now, 'second')
  if (diff <= 0 && r.isActive) {
    if (!r.triggered) {
      r.triggered = true
      emitter.emit('showReminder', { r })
    }
    return '已到期'
  }
  const h = String(Math.floor(diff / 3600)).padStart(2, '0')
  const m = String(Math.floor((diff % 3600) / 60)).padStart(2, '0')
  const s = String(diff % 60).padStart(2, '0')
  return `${h}:${m}:${s}`
}

const isExpired = (r) => getCountdown(r) === '已结束'
const formatNextTime = (r) =>
    getNextReminderTime(r)?.format('MM-DD HH:mm:ss') || '无'

/* 弹窗控制 */
const openAddDialog = () => {
  isEdit.value = false
  Object.assign(form.value, {
    reminderId: null,
    elderlyUserId: null,
    familyUserId: currentUser.value.userId,
    medicationName: '',
    dosage: '',
    frequency: '每天',
    reminderTime: '08:00:00',
    reminderDays: [],
    startDate: '',
    endDate: '',
    remark: '',
    isActive: 1
  })
  dialogVisible.value = true
}

const openEditDialog = (r) => {
  isEdit.value = true
  Object.assign(form.value, {
    ...r,
    reminderDays: r.reminderDays.split(','),
    reminderTime: dayjs(r.reminderTime, 'HH:mm:ss').format('HH:mm:ss')
  })
  dialogVisible.value = true
}

const submitForm = async () => {
  const payload = {
    ...form.value,
    reminderDays: form.value.reminderDays.join(','),
    familyUserId: currentUser.value.userId // 关键：用当前登录用户
  }

  const url = isEdit.value
      ? `${BASE_URL}/api/v1/family_user/medication_reminder/update`
      : `${BASE_URL}/api/v1/family_user/medication_reminder/add`

  await axios.post(url, payload, {
    headers: { Authorization: `Bearer ${token}` }
  })

  ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
  dialogVisible.value = false

  await loadReminders()
}

const deleteReminder = async (id) => {
  await ElMessageBox.confirm('确定删除该提醒吗？')
  await axios.post(
      `${BASE_URL}/api/v1/family_user/medication_reminder/delete/${id}`,
      {},
      { headers: { Authorization: `Bearer ${token}` } }
  )
  ElMessage.success('已删除')
  dialogVisible.value = false
  loadReminders()
}

const toggleStatus = async (r) => {
  const newStatus = r.isActive === 1 ? 0 : 1
  await axios.post(
      `${BASE_URL}/api/v1/family_user/medication_reminder/toggleStatus`,
      null,
      {
        params: { reminderId: r.reminderId, isActive: newStatus },
        headers: { Authorization: `Bearer ${token}` }
      }
  )
  ElMessage.success(newStatus ? '已启用' : '已禁用')
  loadReminders()
  dialogVisible.value = false
}

/* 生命周期 */
onMounted(() => {
  handleSearch()
  loadReminders()
  timer = setInterval(() => {
    reminderList.value = [...reminderList.value]
  }, 1000)
})

onUnmounted(() => {
  clearInterval(timer)
})
</script>

<style scoped>
.reminder-container {
  padding: 20px;
}
.query-bar {
  margin-bottom: 20px;
}
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}
.card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}
.card:hover {
  transform: translateY(-2px);
}
.reminder-card.expired {
  background-color: #ffecec;
  border: 1px solid #f56c6c;
}
.countdown {
  font-size: 18px;
  color: #409eff;
  margin: 8px 0;
}
.add-card {
  border: 2px dashed #ccc;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.add-card:hover {
  border-color: #409eff;
  color: #409eff;
}
.plus-icon {
  font-size: 48px;
  font-weight: bold;
}
.label {
  margin-top: 8px;
  font-size: 14px;
}
</style>